package com.nineclock.auth.intergration.processor;

import com.nineclock.auth.intergration.entity.IntergrationAuthenticationEntity;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.system.feign.SysUserFeign;
import com.nineclock.system.dto.SysUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 手机验证码认证处理器
 */
@Component
public class SmsAuthenticationProcessor implements AuthenticationProcessor {

    @Autowired
    private SysUserFeign userFeign;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public Boolean support(IntergrationAuthenticationEntity entity) {

        if (entity != null && entity.getAuthType() != null && entity.getAuthType().equals("sms")) {
            return true;
        }
        return false;
    }

    @Override
    public SysUserDTO authenticate(IntergrationAuthenticationEntity entity) {

        // 获取手机号、验证码
        String mobile = entity.getAuthParameter("mobile");
        String password = entity.getAuthParameter("password"); // 验证码

        if(StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        // 校验认证码是否正确，后续会从redis取出验证码，和传进来验证码进行对比
        String redisCode = redisTemplate.opsForValue().get(SMSConstant.SMS_LOGIN_KEY_PREFIX + mobile);
        if (!StringUtils.isEmpty(redisCode) && redisCode.equals(password)) {

            // 调用系统微服务接口，根据手机号查询用户信息
            SysUserDTO userDTO = userFeign.queryUser(mobile).getData();

            // 现在userDTO中的password是一个加密后的密码，而传进来的password是一个验证码
            userDTO.setPassword(passwordEncoder.encode(password));

            return userDTO;

        }else{
            throw new NcException(ResponseEnum.INVALID_VERIFY_CODE);
        }

    }
}
